#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Created on 17-12-26
@author: yzw
@desc:
"""
import json

from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from blog_yzw.blog_app.models import Article, BlogPv, Classify
from blog_yzw.blog_app.utils import get_id


# 跳转404
def page_not_found(request):
	return render(request, '404.html')


# 跳转首页
def index(request):
	return render(request, 'index.html')


# 后台首页
def backstage_index(request):
	if 'phone' in request.session and 'name' in request.session:
		context = {'name': request.session.get('name')}
		return render(request, 'backstage_index.html', context)
	else:
		return render(request, 'login.html')


# 后台首页1
def menu_index(request):
	return render(request, 'menu_index.html')


# 首页博客列表
@csrf_exempt
def index_blog_list(request):
	data_list = []
	blog_obj = Article.objects.all().order_by('-create_time')
	if blog_obj.exists():
		for obj in blog_obj:
			data_dict = {'title': obj.title, 'create_time': obj.create_time.strftime('%Y-%m-%d %H:%M:%S'),
			             'author': obj.author, 'id': obj.id}
			pv_obj = BlogPv.objects.filter(article_id=obj.id)[0:1]
			if pv_obj.exists():
				pv_num = pv_obj[0].pv_num
			else:
				pv_num = 0
			data_dict['pv_num'] = pv_num
			classify_obj = Classify.objects.filter(id=obj.classify_id)[0:1]
			if classify_obj.exists():
				classify = classify_obj[0].name
			else:
				classify = '其他'
			data_dict['classify'] = classify
			data_list.append(data_dict)

		return HttpResponse(json.dumps(data_list), content_type="application/json")


# 博客详情
def index_blog_details(request):
	if 'id' in request.GET:
		blog_id = request.GET['id']
		blog_obj = Article.objects.filter(id=blog_id)[0:1]
		if blog_obj.exists():
			obj = blog_obj[0]
			data = {}
			classify_obj = Classify.objects.filter(id=obj.classify_id)
			if classify_obj.exists():
				classify = classify_obj[0].name
			else:
				classify = '其他'

			pv_obj = BlogPv.objects.filter(article_id=blog_id)
			if pv_obj.exists():
				# 更新浏览数
				pv_num = pv_obj[0].pv_num
				pv_num = int(pv_num) + 1
				pv_obj.update(pv_num=pv_num)
			else:
				BlogPv.objects.create(id=get_id(), pv_num=1, article_id=blog_id)
				pv_num = 1
			data['title'] = obj.title
			data['content'] = obj.content
			data['create_time'] = obj.create_time.strftime('%Y-%m-%d %H:%M:%S')
			data['classify'] = classify
			data['pv_num'] = pv_num
			data['author'] = obj.author
			return render(request, 'index_blog_details.html', data)
	return render(request, 'index_blog_details.html')
